var gPendingCallbacks = [];
var bkg = chrome.extension.getBackgroundPage();

chrome.webRequest.onAuthRequired.addListener(handleAuthRequest,
	{urls: ["<all_urls>"]}, ["asyncBlocking"]);

function processPendingCallbacks() {
	var cb_data = gPendingCallbacks.pop();
	var credentials_rx = /([A-z0-9]*):?([A-z0-9]*)@.+/i;
	var credentials = credentials_rx.exec(cb_data.details.url);
	
	if(credentials!=null && credentials[1]!=""){ 
		//username
		var headerData = {username: credentials[1]};
		if(credentials[2]!=""){
			//password
			headerData.password = credentials[2];
		}
		cb_data.callback({authCredentials:headerData});
	} else {
		cb_data.callback({});
	}
}

function handleAuthRequest(details, callback) {
	gPendingCallbacks.push({callback:callback, details:details});
	processPendingCallbacks();
}